package com.example.mqtt.controller;

import com.example.mqtt.service.MqttService;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/system/mqtt")
public class MqttController {
    @Autowired
    private MqttService mqttService;
    private static final Logger logger = LoggerFactory.getLogger(MqttController.class);

    @PostMapping("/send")
    public ResponseEntity<?> sendMessage(
            @RequestParam String topic,
            @RequestParam String message
    ) {
        try {
            mqttService.publish(topic, message);
            logger.info("消息发送成功: {}", message);
            return ResponseEntity.ok(Map.of(
                    "status", "success",
                    "topic", topic,
                    "message", message
            ));
        } catch (MqttException e) {
            logger.error("消息发送失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "MQTT通信异常"));
        }
    }

    @PostMapping("/subscribe")
    public ResponseEntity<?> subscribeToTopic(
            @RequestParam String topic,
            @RequestParam(required = false, defaultValue = "1") int qos
    ) {
        try {
            mqttService.subscribe(topic);
            return ResponseEntity.ok(Map.of(
                    "status", "subscribed",
                    "topic", topic,
                    "qos", qos
            ));
        } catch (MqttException e) {
            logger.error("订阅失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("error", "主题订阅失败"));
        }
    }
}